import { addUserUsingPost } from "@/api/userController";
import { ProColumns, ProTable } from "@ant-design/pro-components";
import { message, Modal, Upload } from "antd";
import React, { useState } from "react";
import { PlusOutlined } from "@ant-design/icons";
import type { UploadFile, RcFile, UploadProps } from "antd/es/upload/interface";
import { uploadFileUsingPost } from "@/api/fileController";

interface Props {
  visible: boolean;
  columns: ProColumns<API.User>[];
  onSubmit: (values: API.UserAddRequest) => void;
  onCancel: () => void;
}

/**
 * 添加用户
 * @param fields 用户信息
 */
const handleAdd = async (fields: API.UserAddRequest) => {
  const hide = message.loading("正在添加");
  try {
    await addUserUsingPost(fields);
    hide();
    message.success("创建成功");
    return true;
  } catch (error: any) {
    hide();
    message.error("创建失败，" + error.message);
    return false;
  }
};
// 在组件顶部添加正则表达式常量
const VALIDATE_REGEX = {
  USERNAME: /^[\u4e00-\u9fa5a-zA-Z_-][\u4e00-\u9fa5a-zA-Z0-9_-]{1,15}$/, // 2-16位中英文、数字、下划线、短横线
  ACCOUNT: /^[a-zA-Z_][a-zA-Z0-9_]{3,19}$/, // 4-20位字母、数字、下划线
  PROFILE: /^[\s\S]{1,200}$/, // 1-200个任意字符（包括换行）
};

/**
 * 创建用户弹窗
 */
const CreateModal: React.FC<Props> = (props) => {
  const { visible, columns, onSubmit, onCancel } = props;
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [imageUrl, setImageUrl] = useState<string>();
  const [uploading, setUploading] = useState(false);

  /**
   * 自定义上传实现
   */
  const customRequest: UploadProps["customRequest"] = async ({
    file,
    onSuccess,
    onError,
  }) => {
    const hide = message.loading("正在上传头像...");
    setUploading(true);

    try {
      const res = await uploadFileUsingPost(
        { biz: "user_avatar" }, // params 参数
        {}, // body 参数
        file as File, // file 参数
      );
      // 根据实际接口返回结构调整
      // 假设返回格式为 { data: { url: string } }
      console.log(res);
      const url = res.data;
      if (!url) throw new Error("获取图片URL失败");
      setImageUrl(url);
      onSuccess?.(res.data);
      message.success("头像上传成功");
    } catch (error: any) {
      message.error("上传失败: " + error.message);
      onError?.(error);
    } finally {
      hide();
      setUploading(false);
    }
  };

  /**
   * 上传前校验
   */
  const beforeUpload = (file: RcFile) => {
    const isImage = file.type.startsWith("image/");
    if (!isImage) {
      message.error("只能上传图片文件!");
      return Upload.LIST_IGNORE;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片大小不能超过2MB!");
      return Upload.LIST_IGNORE;
    }
    return true;
  };

  /**
   * 处理文件变化
   */
  const handleChange: UploadProps["onChange"] = ({ file }) => {
    if (file.status === "removed") {
      setImageUrl(undefined);
    }
    setFileList([file]);
  };

  /**
   * 修改columns配置，将头像字段改为上传组件
   */
  const modifiedColumns = columns.map((column) => {
    if (column.dataIndex === "userAvatar") {
      return {
        ...column,
        renderFormItem: () => (
          <Upload
            name="avatar"
            listType="picture-card"
            fileList={fileList}
            customRequest={customRequest}
            beforeUpload={beforeUpload}
            onChange={handleChange}
            maxCount={1}
            disabled={uploading}
          >
            {imageUrl ? (
              <img
                src={imageUrl}
                alt="avatar"
                style={{
                  width: "100%",
                  height: "100%",
                  objectFit: "cover",
                }}
              />
            ) : (
              <div>
                {/*<PlusOutlined />*/}
                <div style={{ marginTop: 8 }}>上传头像</div>
              </div>
            )}
          </Upload>
        ),
      };
    }
    return column;
  });

  /**
   * 处理表单提交
   */
  const handleSubmit = async (values: API.UserAddRequest) => {
    console.log(values);

    const userInfo = {
      userAccount: "",
      userName: "",
      userProfile: "",
      userRole: "",
    };
    // @ts-ignore
    userInfo.userAccount = values.userAccount;

    // @ts-ignore
    userInfo.userName = values.userName;

    // @ts-ignore
    userInfo.userProfile = values.userProfile;

    // @ts-ignore
    userInfo.userRole = values.userRole;

    const validateFields = () => {
      if (
        !userInfo.userName ||
        !VALIDATE_REGEX.USERNAME.test(userInfo.userName.trim())
      ) {
        message.error(
          "（用户名首字母非数字，2-16位中英文、数字、下划线、短横线）",
        );
        return false;
      }

      if (
        !userInfo.userAccount ||
        !VALIDATE_REGEX.ACCOUNT.test(userInfo.userAccount.trim())
      ) {
        message.error("账号首字母非数字，4-20位字母、数字、下划线");
        return false;
      }

      if (
        !userInfo.userProfile ||
        !VALIDATE_REGEX.PROFILE.test(userInfo.userProfile.trim())
      ) {
        message.error("简介长度应在1-200个字符之间");
        return false;
      }

      return true;
    };
    if (!validateFields()) return false;

    if (!imageUrl) {
      message.warning("请上传头像");
      return;
    }
    const submitValues = {
      ...userInfo,
      userAvatar: imageUrl,
    };

    const success = await handleAdd(submitValues);
    if (success) {
      onSubmit?.(submitValues);
      // 重置表单状态
      setFileList([]);
      setImageUrl(undefined);
    }
  };

  return (
    <Modal
      destroyOnClose
      title="创建用户"
      open={visible}
      footer={null}
      onCancel={() => {
        // 重置状态
        setFileList([]);
        setImageUrl(undefined);
        onCancel?.();
      }}
      width={800}
    >
      <ProTable
        type="form"
        columns={modifiedColumns}
        onSubmit={handleSubmit}
        rowKey="id"
        form={{
          // 自动清除表单数据
          preserve: false,
        }}
      />
    </Modal>
  );
};

export default CreateModal;
